package com.ly.blog_third.email;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.Map;

/**
 * 核心对接点
 * @author ly create at 2021/6/29 - 12:52
 **/
@Slf4j
@Component
public class EmailManagerService {

    @Autowired
    JavaMailSender javaMailSender;

    @Value("${spring.mail.username}")
    private String from;

    /**
     * 发送简单邮件
     * @param subject 主题
     * @param msg 信息体 - txt格式，不支持html
     * @param to 目标邮箱
     */
    public void sendSimpleEmail(String subject,String msg,String ... to){

        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        simpleMailMessage.setSubject(subject);
        simpleMailMessage.setText(msg);
        simpleMailMessage.setFrom(from);
        simpleMailMessage.setTo(to);
        log.info("【简单邮箱正式发送】 --开始 -  from：{}，to:{}",from,to);
        javaMailSender.send(simpleMailMessage);
        log.info("【简单邮箱正式发送】 --结束 - from：{}，to:{}",from,to);
    }


    /**
     * 发送复杂邮件
     * @param subject 主题
     * @param msg 信息体 - txt/html
     * @param isHtml 信息体 ,是否支持html
     * @param fileInfo 附件信息 - 文件名+文件实体
     * @param to 目标邮箱
     */
    public void sendEmail(String subject, String msg, boolean isHtml, Map<String,File> fileInfo, String ... to) {

        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        try {
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage,true);
            mimeMessageHelper.setSubject(subject);
            mimeMessageHelper.setText(msg,isHtml);
            if(fileInfo != null){
                log.info("【复杂邮件配置文件】 - 开始");
                fileInfo.entrySet().forEach(item->{
                    try {
                        mimeMessageHelper.addAttachment(item.getKey(),item.getValue());
                    } catch (MessagingException e) {
                        e.printStackTrace();
                        log.info("【复杂邮件配置文件】 - 失败 - 文件名:{}",item.getKey());
                    }
                });
                log.info("【复杂邮件配置文件】 - 结束");
            }
            mimeMessageHelper.setFrom(from);
            mimeMessageHelper.setTo(to);
        } catch (MessagingException e) {
            e.printStackTrace();
        }

        log.info("【复杂邮箱正式发送】 --开始 -  from：{}，to:{}",from,to);
        long s = System.currentTimeMillis();
        javaMailSender.send(mimeMessage);
        long b = System.currentTimeMillis() - s;
        log.info("【复杂邮箱正式发送】 --成功 -  from：{}，to:{}，耗时：{}秒",from,to,b/1000);
    }

}
